package com.terrence.sso.token.server.servlet;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.terrence.sso.token.common.utils.StringUtils;
import com.terrence.sso.token.common.utils.URLUtils;
import com.terrence.sso.token.common.utils.UUIDUtil;
import com.terrence.sso.token.server.Constant;
import com.terrence.sso.token.server.cache.SSOSessionCache;
import com.terrence.sso.token.server.service.SidCookieService;
import com.terrence.sso.token.server.service.UserVerifyService;
import com.terrence.sso.token.server.vo.Token;

public class SSOLoginServlet extends HttpServlet {
    private static final long serialVersionUID = -3170191388656385924L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //从登陆页面接收的参数
    	String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        String redirectUrl = request.getParameter("redirectUrl");
        System.out.println("ServerLogin: "+redirectUrl );
        //验证用户是否有效
        if(UserVerifyService.isValid(userName, password)){
        	//创建sid
        	String sid = UUIDUtil.getUuid();
        	//创建cookie
        	Cookie cookie = new Cookie(Constant.COOKIE_NAME,sid);
            cookie.setPath(request.getServerName());
            response.addCookie(cookie);
            //创建token
            String token = Token.getInstance(sid).toToken();
            //缓存Session
            SSOSessionCache.put(sid, token);
            //重定向到业务系统的验证URL
            HashMap<String,String> params = new HashMap<String,String>();
            params.put("token", token);
            response.sendRedirect(URLUtils.appendParams(redirectUrl, params));
        }
        //检查服务端的Cookie是否存在
        else if(StringUtils.isNotEmpty(SidCookieService.getSid(request))){
        	String sid = SidCookieService.getSid(request);
        	String token = SSOSessionCache.get(sid);
            //重定向到业务系统的验证URL
            HashMap<String,String> params = new HashMap<String,String>();
            params.put("token", token);
            response.sendRedirect(URLUtils.appendParams(redirectUrl, params));
        }
        //跳转到登录页面
        else{
            response.sendRedirect("/SSOServer/index.jsp"+"?redirectUrl="+redirectUrl);
        }
    }

}